const { execSQL } = require('../../db/mysql');

//获取用户列表方法
function getList() {
    const sql = 'select * from user';
    return execSQL(sql);
}

//获取详情数据方法
const getDetail = id => {
    const sql = `select * from user where user_id='${id}'`;
    return execSQL(sql);
}

//创建新用户
const createNewUser = (userData = {}) => {
    const account = userData.account; 
    const password = userData.password;
    const email = userData.email;
    const phone = userData.phone;
    const avatar = userData.avatar;
    const money = userData.money;
    const addr = userData.addr;

    const sql = `insert into user (user_account, user_password, user_avatar, email, phone, money, user_addr) values ('${account}', '${password}', '${avatar}', '${email}', '${phone}','${money}','${addr}')`;
    return execSQL(sql).then(insertedResult => {
        return {
            id: insertedResult.insertId
        }
    });
}

//更新用户
const updateUser = (id, userData = {}) => {
    const account = userData.account;
    const password = userData.password;
    const email = userData.email;
    const phone = userData.phone;
    const avatar = userData.avatar;
    const money = userData.money;
    const addr = userData.addr;

    const sql = `update user set user_account='${account}', user_password='${password}', user_avatar='${avatar}', email='${email}', phone='${phone}', user_money=${money}, user_addr='${addr}' where user_id=${id}`;
    return execSQL(sql).then(updateResult => {
        if (updateResult.affectedRows > 0) {
            return true;
        }
        return false;
    }); 
}
//支付扣款
const userPay = (id, userData = {}) => {
    const money = userData.user_money;

    const sql = `update user set user_money=${money} where user_id=${id}`;
    return execSQL(sql).then(updateResult => {
        if (updateResult.affectedRows > 0) {
            return true;
        }
        return false;
    });
}

//删除用户
const deleteUser = id => {
    const sql = `delete from user where user_id=${id}`
    return execSQL(sql).then(deleteResult => {
        if (deleteResult.affectedRows > 0) {
            return true;
        }
        return false;
    })
}

//用户登录
const userLogin = (userAccount, password) => {
    const sql = `select * from user where user_account='${userAccount}'`;
    // console.log(execSQL(sql));
    return execSQL(sql);
}

//导出方法
module.exports = { 
    getList,
    getDetail,
    createNewUser,
    updateUser,
    deleteUser,
    userLogin,
    userPay
}